import { RefObject, useEffect, useState } from "react";

export function useDebounce(value: any, delay = 300) {
	const [debounceValue, setDebouncedValue] = useState(value);
	useEffect(() => {
		const handler = setTimeout(() => {
			setDebouncedValue(value);
		}, delay);
		return () => {
			clearTimeout(handler);
		};
	}, [value, delay]);
	return debounceValue;
}

export function useClickOutside(ref: RefObject<HTMLElement>, handler: Function) {
	useEffect(() => {
		const listener = (event: MouseEvent) => {
			if (!ref.current || ref.current.contains(event.target as Node)) {
				return;
			}
			handler(event);
		};
		document.addEventListener("click", listener);
		return () => document.removeEventListener("click", listener);
	}, [ref, handler]);
}